package tgc.edu.exam.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tgc.edu.exam.custom.CommonService;
import tgc.edu.exam.entity.Menu;
import tgc.edu.exam.repository.MeunRepository;
import tgc.edu.exam.security.UserUtils;

@Service
public class MenuService extends CommonService<Menu, Integer>{

	@Autowired
	public MeunRepository dao;
	@Autowired
	private UserUtils userUtils;
	
	public List<Menu> findAllMenu() {
		List<Menu> menus;
		if(userUtils.hasRole("ROLE_DVP")) {
			menus=dao.findByParentIsNullOrderByIdx1();
		}else {
			menus=auditMenu(dao.findByParentIsNullOrderByIdx1());
		}
		return menus;
	}
	
	private List<Menu> auditMenu(List<Menu> menus) {
		
		List<Menu> list=new ArrayList<>();
		for (Menu menu : menus) {
			String code = menu.getRole().getCode();
			if(userUtils.hasRole(code)) {
				list.add(menu);
				if(menu.getChildren()!=null&&!menu.getChildren().isEmpty()) {
					menu.setChildren(auditMenu(menu.getChildren()));
				}
			}
		}
		return list;
	}

}
